package com.xnew.ssoApi.service.impl;


import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.xnew.bean.common.AuUserRole;
import com.xnew.bean.common.SysOrgUserInfo;
import com.xnew.bean.common.SysUserInfo;
import com.xnew.bean.common.T10MemOrgLinkmanInfo;
import com.xnew.constant.Constant;
import com.xnew.encrypt.Sm3Encrypt;
import com.xnew.entity.memberinfo.MemshpApplyInfoma;
import com.xnew.entity.ssoApi.*;
import com.xnew.ssoApi.entity.Menu;
import com.xnew.ssoApi.mapper.*;
import com.xnew.ssoApi.service.SsoApiService;
import com.xnew.sysOrgUser.mapper.T10MemOrgLinkmanInfoMapper;
import com.xnew.sysOrgUser.mapper.T10SysOrgUserInfoMapper;
import com.xnew.utils.ApiHttp;
import com.xnew.utils.HttpClientUtil;
import com.xnew.utils.IdUtils;
import com.xnew.utils.RedisUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.expression.ParseException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class SsoApiServiceImpl implements SsoApiService {
    @Value("${SSO.Client_id}")
    private String Client_id ; //子系统代码appid:lay1g9z439
    @Value("${SSO.Client_secret}")
    private String Client_secret ; //公钥
    @Value("${SSO.Grant_type}")
    private String Grant_type ; //
    @Value("${SSO.sso_ip}")
    private String sso_ip ;//接口公网IP
    @Value("${SSO.Redirect_uri}")
    private String Redirect_uri ; //子系统链接
    @Value("${SSO.tokenUrl}")
    private String tokenUrl ; //子系统请求token接口
    @Value("${SSO.userinfoUrl}")
    private String userinfoUrl ; //子系统通过token获取用户信息接口
    @Value("${SSO.updateTokenUrl}")
    private String updateTokenUrl ; //刷新Token
    @Value("${SSO.updateAccessTokenUrl}")
    private String updateAccessTokenUrl ; //刷新accessToken
    @Value("${SSO.PlatformOrgRegUrl}")
    private String PlatformOrgRegUrl ; //平台机构账户注册
    @Value("${SSO.PlatformPersonalRegUrl}")
    private String PlatformPersonalRegUrl ; //平台个人账户注册
    @Value("${SSO.PlatformSupvRegUrl}")
    private String PlatformSupvRegUrl ; //平台监管账户注册
    @Value("${SSO.OrgAccountStateEditUrl}")
    private String OrgAccountStateEditUrl ; //账号状态变更
    @Value("${SSO.AccountEditUrl}")
    private String AccountEditUrl ; //账号信息修改
    @Value("${SSO.SubNewsUrl}")
    private String SubNewsUrl ; //	子系统门户公告
    @Value("${SSO.SubNewsDelUrl}")
    private String SubNewsDelUrl ; //	子系统门户公告删除
    @Value("${SSO.AccountEditOrgCodeUrl}")
    private String AccountEditOrgCodeUrl ; //	机构信息修改
    @Resource
    private SysUserInfoMapper t61SysUserInfoMapper;
    @Resource
    private T10SysOrgUserInfoMapper sysOrgUserInfoMapper;
    @Resource
    private OrgInfoTmpMapper t10OrgInfoTmpMapper;
    @Resource
    private MemshpApplyInfomaMapper t10MemshpApplyInfomaMapper;
    @Resource
    private T10MemOrgLinkmanInfoMapper t10MemOrgLinkmanInfoMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private SysUserInfoMapper sysUserInfoMapper;




    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 根据code获取平台token值
     * @return
     */
    public TokenDo getToken(String code) throws Exception {
        //平台获取token地址
        System.out.println("平台获取token地址 getToken(String tokenUrl,String code):" + code);
        TokenDo tokenDo  = null;
        TokenVo tokenVo = this.setTokenVo(code);
        System.out.println("--------------------获取token--------------------");
        // 根据 code 请求 token
        ResultDo resultDo = ApiHttp.getResult("http://" + sso_ip + tokenUrl, tokenVo);
        if (null != resultDo){
            if (null != resultDo.getCode() && 200 == resultDo.getCode()){
                Object data = resultDo.getData()!=null?resultDo.getData():null;
                if(data!=null){
                    tokenDo = JSONObject.parseObject(data+"", TokenDo.class);
                    System.out.println("data---" + data);
                }
            }
        }
        return tokenDo;
    }

    /**
     * 调用平台接口，获取用户信息
     * @return 用户信息
     */
    public LoginDo getUserInfo(String accessToken) throws Exception {
        ResultDo resultUserInfo = null;
        System.out.println("调用平台接口，获取用户信息 getUserInfo(String url,String accessToken,String appId):" + accessToken);
        // 根据 token 请求 userInfo
        LoginDo userInfo = null;
        HttpClientUtil httpClientUtil = new HttpClientUtil();
        Map<String,String> params = new HashMap<String,String>();
        params.put("access_token",accessToken);
        params.put("appId",Client_id);
        Map<String,String> returnMap = httpClientUtil.doGet("http://" + sso_ip + userinfoUrl, params, "utf-8");
        System.out.println("returnMap:" + returnMap);
        if (returnMap!=null){
            String result = returnMap.get("result")!=null?returnMap.get("result").trim():"";
            String status = returnMap.get("status")!=null?returnMap.get("status").trim():"";
            if(status.equals("200")){
                if(!result.equals("")){
                    resultUserInfo = JSONObject.parseObject(result,ResultDo.class);
                }
            }
        }
        //resultUserInfo = ApiHttp.getResultDo(url, params);
        if (null != resultUserInfo){
            if (null!=resultUserInfo.getCode() && 200 == resultUserInfo.getCode()){
                if (null!=resultUserInfo.getData()){
                    Object data = resultUserInfo.getData();
                    userInfo = JSONObject.parseObject(data+"", LoginDo.class);
                    System.out.println("data---" + data);
                    System.out.println("userInfo---" + userInfo.getUserType());
                    System.out.println("userName---" + userInfo.getUserName());
                    System.out.println("userType---" + userInfo.getUserType());
                    System.out.println("orgCode---" + userInfo.getOrgCode());
                    System.out.println("orgName---" + userInfo.getOrgName());
                }
            }
        }
        return userInfo;
    }



    /**
     * 调用平台接口，刷新 ResultDo
     * @return 新token(String)
     */
    public ResultDo refreshToken(String token) throws Exception {
        ResultDo resultInfo = null;
        TokenDo tokenDo = null;
        System.out.println("调用平台接口，调用平台接口，刷新 token refreshToken(String token):" + token);
        HttpClientUtil httpClientUtil = new HttpClientUtil();
        Map<String,String> params = new HashMap<String,String>();
        params.put("access_token",token);
        params.put("appId",Client_id);
        Map<String,String> returnMap = httpClientUtil.doGet("http://" + sso_ip + updateTokenUrl, params, "utf-8");
        System.out.println("returnMap:" + returnMap);
        if (returnMap!=null){
            String result = returnMap.get("result")!=null?returnMap.get("result").trim():"";
            resultInfo = JSONObject.parseObject(result,ResultDo.class);
        }
        return resultInfo;
    }

    /**
     * 调用平台接口，刷新 access_token
     * @return 新access_token(String)
     */
    public TokenDo refreshAccessToken(String refresh_token) throws Exception {
        ResultDo resultInfo = null;
        TokenDo tokenDo = null;
        //System.out.println("调用平台接口，调用平台接口，刷新 access_token refreshAccessToken(String refresh_token):" + refresh_token);
        HttpClientUtil httpClientUtil = new HttpClientUtil();
        Map<String,String> params = new HashMap<String,String>();
        params.put("refresh_token",refresh_token);
        params.put("appId",Client_id);
        Map<String,String> returnMap = httpClientUtil.doGet("http://" + sso_ip + updateAccessTokenUrl, params, "utf-8");
        //System.out.println("returnMap:" + returnMap);
        if (returnMap!=null){
            String result = returnMap.get("result")!=null?returnMap.get("result").trim():"";
            String status = returnMap.get("status")!=null?returnMap.get("status").trim():"";
            if(status.equals("200")){
                if(!result.equals("") && !result.equals("{}")){
                    resultInfo = JSONObject.parseObject(result,ResultDo.class);
                    Object data = resultInfo.getData()!=null?resultInfo.getData():null;
                    if(data!=null){
                        tokenDo = JSONObject.parseObject(data+"", TokenDo.class);
                        System.out.println("data---" + data);
                        System.out.println("tokenDo.getAccess_token()---" + tokenDo.getAccess_token());
                        System.out.println("tokenDo.getExpires_in()---" + tokenDo.getExpires_in());
                        System.out.println("tokenDo.getRefresh_token()---" + tokenDo.getRefresh_token());
                        System.out.println("tokenDo.getId_token()---" + tokenDo.getId_token());
                    }
                }
            }
        }
        //System.out.println("resultInfo:" + resultInfo.toString());
        return tokenDo;
    }

    public ResultDo getResultDo(String url, Object object) throws UnsupportedEncodingException {
        ResultDo resultDo = null;
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        String jsonString = com.alibaba.fastjson.JSON.toJSONString(object);
        StringEntity entity = new StringEntity(jsonString, "UTF-8");
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                resultDo = JSONObject.parseObject(EntityUtils.toString(responseEntity,"UTF-8"),ResultDo.class);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultDo;
    }

    public TokenVo setTokenVo(String code) {
        TokenVo tokenVo = new TokenVo();
        tokenVo.setClient_id(Client_id); //appid
        tokenVo.setClient_secret(Client_secret); //公钥
        tokenVo.setCode(code); //授权码code
        tokenVo.setGrant_type(Grant_type);  //固定值
        tokenVo.setRedirect_uri(Redirect_uri + "?code=" + code); //登录后要跳转的页面
        return tokenVo;
    }


    /**
     * 子系统机构账号注册
     * @return ResultDo   msg 返回信息   code 返回值状态码
     */
    public ResultDo SubSystemOrgReg(Map<String,Object> param) throws Exception {
        System.out.println("=================子系统机构账号注册  SubSystemOrgReg(SubSystemOrgRegVo params):" + param.toString() + "=================");
        ResultDo result = new ResultDo();
        String msg = "操作成功";//返回信息
        String code = "200";//返回状态码
        //查询机构表是否存在
        SysOrgUserInfo sysOrgUserInfo = sysOrgUserInfoMapper.selectData(param);
        if(sysOrgUserInfo!=null){
            result.setMsg("机构已存在！不能重复注册！");
            result.setCode(Integer.parseInt("0"));
            return result;
        }

        String aur_id = IdUtils.getIncreaseIdByNanoTime();
        String au_id = param.get("userInfoNo")!=null?(String)param.get("userInfoNo"):"" ; //登录用户主键
        String ar_id = "1350901729190049318" ; //角色主键
        if("".equals(aur_id)){
            System.out.println("aur_id is null!");
            result.setMsg("aur_id is null！");
            result.setCode(Integer.parseInt("0"));
            return result;
        }
        if("".equals(au_id)){
            System.out.println("au_id is null!");
            result.setMsg("au_id is null！");
            result.setCode(Integer.parseInt("0"));
            return result;
        }
        System.out.println("=================删除用户表一样的数据=================");//删除用户表一样的数据
        t61SysUserInfoMapper.deleteData(param);

        System.out.println("=================增加机构用户=================");//增加机构用户
        t10OrgInfoTmpMapper.addData(param);

        System.out.println("=================增加登录用户=================");//增加登录用户
        String user_info_no = param.get("userInfoNo")!=null?(String)param.get("userInfoNo"):"";// 主键
        String login_name = param.get("loginName")!=null?(String)param.get("loginName"):"" ;//  登录名
        String pwd = param.get("pwd")!=null?(String)param.get("pwd"):"" ;//  登录密码 SM4加密的
        String user_state = Constant.USER_STATUS_CODE_0;//  用户状态  0
        String user_type = "33";//  用户类型 33 : 临时用户
        String user_name = param.get("userName")!=null?(String)param.get("userName"):"" ;//  用户名称
        String is_sso_user = "2";//  是否单点登录 1是 2不是
        String lock_times = "0";//  锁定次数 0
        String openId = param.get("openId")!=null?(String)param.get("openId"):"" ;
        String orgId = param.get("orgId")!=null?(String)param.get("orgId"):"" ;
        //创建机构用户
        SysUserInfo sysUserInfo = new SysUserInfo();
        sysUserInfo.setUserName(user_name);//用户名
        sysUserInfo.setUserInfoNo(user_info_no);//id
        sysUserInfo.setOrgUserNo(orgId);//机构用户信息id
        sysUserInfo.setCreateUserNo(user_info_no);//创建人
        sysUserInfo.setCreateTime(DateUtil.now());//创建时间
        sysUserInfo.setModyTime(DateUtil.now());//修改时间
        sysUserInfo.setRegIp(InetAddress.getLocalHost().getHostAddress());//ip
        sysUserInfo.setLoginName(login_name);//登录名
        String salt = Sm3Encrypt.getSaltString();
        sysUserInfo.setUserState(user_state);//用户状态
        sysUserInfo.setSalt(salt);
        sysUserInfo.setOpenId(openId);
        sysUserInfo.setIsSsoUser(is_sso_user);
        sysUserInfo.setLockTimes(lock_times);
        sysUserInfo.setUserType(user_type);
        // 新密码
        String newPassword = Sm3Encrypt.encrypt(salt, pwd, login_name);
        System.out.println("=========================================================================");
        System.out.println("===========================" + newPassword + "===============================");
        System.out.println("=========================================================================");
        sysUserInfo.setPwd(newPassword);//初始密码
        sysUserInfoMapper.insert(sysUserInfo);

        System.out.println("=================增加机构管理员=================");//增加机构管理员
        T10MemOrgLinkmanInfo t10MemOrgLinkmanInfo = new T10MemOrgLinkmanInfo();
        String orgLinkmanNo = param.get("orgLinkmanNo")!=null?(String)param.get("orgLinkmanNo"):"" ;
        String orgUserNo = param.get("orgUserNo")!=null?(String)param.get("orgUserNo"):"" ;
        String linkmanName = param.get("linkmanName")!=null?(String)param.get("linkmanName"):"" ;
        String linkmanMob = param.get("linkmanMob")!=null?(String)param.get("linkmanMob"):"" ;
        String linkmanEml = param.get("linkmanEml")!=null?(String)param.get("linkmanEml"):"" ;
        String userNo = param.get("userNo")!=null?(String)param.get("userNo"):"" ;
        String dtcId = param.get("dtcId")!=null?(String)param.get("dtcId"):"" ;
        String documentNo = param.get("documentNo")!=null?(String)param.get("documentNo"):"" ;
        t10MemOrgLinkmanInfo.setOrgLinkmanNo(orgLinkmanNo);
        t10MemOrgLinkmanInfo.setOrgUserNo(orgUserNo);
        t10MemOrgLinkmanInfo.setLinkmanName(linkmanName);
        t10MemOrgLinkmanInfo.setLinkmanMob(linkmanMob);
        t10MemOrgLinkmanInfo.setLinkmanEml(linkmanEml);
        t10MemOrgLinkmanInfo.setUserNo(userNo);
        t10MemOrgLinkmanInfo.setDtcId(dtcId);
        t10MemOrgLinkmanInfo.setDocumentNo(documentNo);
        t10MemOrgLinkmanInfoMapper.insert(t10MemOrgLinkmanInfo);

        System.out.println("=================增加注册信息=================");//增加注册信息
        MemshpApplyInfoma t10MemshpApplyInfoma = new MemshpApplyInfoma();
        String memshpApplyInfomaNo = param.get("memshpApplyInfomaNo")!=null?(String)param.get("memshpApplyInfomaNo"):"" ;
        String unitName = param.get("unitName")!=null?(String)param.get("unitName"):"" ;
        String org_user_no = param.get("orgId")!=null?(String)param.get("orgId"):"" ;
        t10MemshpApplyInfoma.setMemshpApplyInfomaNo(memshpApplyInfomaNo);
        t10MemshpApplyInfoma.setUnitName(unitName);
        t10MemshpApplyInfoma.setOrgUserNo(org_user_no);
        t10MemshpApplyInfoma.setAddTime(DateUtil.now());
        t10MemshpApplyInfoma.setAddPsnNo(user_info_no);
        t10MemshpApplyInfoma.setAcId("01");
        t10MemshpApplyInfomaMapper.insert(t10MemshpApplyInfoma);

        System.out.println("=================增加用户权限=================");//增加用户权限
        AuUserRole auUserRole = new AuUserRole();
        auUserRole.setAurId(aur_id);
        auUserRole.setAuId(au_id);
        auUserRole.setArId(ar_id);
        auUserRole.setAurCreateTime(DateUtil.now());
        auUserRole.setAurCreateUser("admin");
        auUserRole.setAurType("02");
        userRoleMapper.insert(auUserRole);
        result.setMsg(msg);
        result.setCode(Integer.parseInt(code));
        return result;
    }

    /**
     * 子系统个人账户注册
     * @return ResultDo   msg 返回信息   code 返回值状态码
     */
    public ResultDo SubSystemPersonalReg(Map<String,Object> param) throws Exception {
        //System.out.println("子系统个人账户注册 SubSystemPersonalReg(SubSystemPersonalRegVo param):" + params.toString());
        ResultDo resultDo = null;
        return resultDo;
    }


    /**
     * 子系统监管账户注册
     * @return ResultDo   msg 返回信息   code 返回值状态码
     */
    public ResultDo SubSystemSupvReg(Map<String,Object> param) throws Exception {
        //System.out.println("子系统监管账户注册 SubSystemSupvReg(SubSystemSupvRegVo param):" + param2.toString());
        String msg = "操作失败！";
        String code = "0";
/*        List<String> resultList = manager.saveSupvRegInfo(params);
        msg = resultList.get(0);
        code = resultList.get(1);
        ResultDo result = new ResultDo();
        result.setMsg(msg);
        result.setCode(Integer.parseInt(code));
        return result;*/
        return null;
    }


    /**
     * 平台机构账户注册
     * @return ResultDo   msg 返回信息   code 返回值状态码
     */
    public ResultDo PlatformOrgReg(PlatformOrgRegVo params) throws Exception {
        System.out.println("平台机构账户注册 PlatformOrgReg(PlatformOrgRegVo params):" + params.toString());
        params.setUserType(2);
        params.setIsVip("0");
        ResultDo resultDo = ApiHttp.getResult("http://" + sso_ip + PlatformOrgRegUrl, params);
        return resultDo;
    }

    /**
     * 平台个人账户注册
     * @return ResultDo   msg 返回信息   code 返回值状态码
     */
    public ResultDo PlatformPersonalReg(PlatformPersonalRegVo params) throws Exception {
        System.out.println("平台个人账户注册  PlatformPersonalReg(PlatformPersonalRegVo params):" + params.toString());
        params.setUserType(1);
        ResultDo resultDo = ApiHttp.getResult("http://" + sso_ip + PlatformPersonalRegUrl, params);
        return resultDo;
    }
    /**
     * 平台监管账户注册
     * @return ResultDo   msg 返回信息   code 返回值状态码
     */
    public ResultDo PlatformSupvReg(PlatformSupvRegVo params) throws Exception {
        System.out.println("平台监管账户注册  PlatformSupvReg(PlatformSupvRegVo params):" + params.toString());
        params.setUserType(3);
        ResultDo resultDo = ApiHttp.getResult("http://" + sso_ip + PlatformSupvRegUrl, params);
        return resultDo;
    }


    /**
     * 账户状态变更
     * @return ResultDo   msg 返回信息   code 返回值状态码
     */
    public ResultDo OrgAccountState(OrgAccountStateVo params) throws Exception {
        System.out.println("账户状态变更  OrgAccountState(OrgAccountStateVo params):" + params.toString());
        params.setAppId(Client_id);
        ResultDo resultDo = ApiHttp.getResult("http://" + sso_ip + OrgAccountStateEditUrl, params);
        return resultDo;
    }
    /**
     * 账户信息修改
     * @return ResultDo   msg 返回信息   code 返回值状态码
     */
    public ResultDo Account(AccountVo params) throws Exception {
        System.out.println("账户信息修改  Account(AccountVo params):" + params.toString());
        params.setAppId(Client_id);
        ResultDo resultDo = ApiHttp.getResult("http://" + sso_ip + AccountEditUrl, params);
        return resultDo;
    }
    /**
     * 机构账户信息修改
     * @return ResultDo   msg 返回信息   code 返回值状态码
     */
    public ResultDo AccountOrg(AccountVo params) throws Exception {
        //System.out.println("账户信息修改  Account(AccountVo params):" + params.toString());
        ResultDo resultDo = ApiHttp.getResult("http://" + sso_ip + AccountEditOrgCodeUrl, params);
        return resultDo;
    }
    /**
     * 子系统门户公告
     * @return ResultDo   msg 返回信息   code 返回值状态码
     */
    public ResultDo SubNews(SubNewsVo params) throws Exception {
        //System.out.println("账户信息修改  SubNews(SubNewsVo params):" + params.toString());
        ResultDo resultDo = ApiHttp.getResult("http://" + sso_ip + SubNewsUrl, params);
        return resultDo;
    }
    /**
     * 子系统门户公告删除
     * @return ResultDo   msg 返回信息   code 返回值状态码
     */
    public ResultDo SubNewsDel(SubNewsVo params) throws Exception {
        //System.out.println("账户信息修改  SubNewsDel(SubNewsVo params):" + params.toString());
        ResultDo resultDo = ApiHttp.getResult("http://" + sso_ip + SubNewsDelUrl, params);
        return resultDo;
    }

    /**
     * pc端登录方法
     * @author yangcd
     * */
    public Map<String, Object> login(String id, String userName, HttpServletRequest request, String loginType) throws Exception{
        SysUserInfo user = null;
        if("wx".equals(loginType)) {
            user = t61SysUserInfoMapper.selectByPrimaryKey(id);
        }else {
            user = t61SysUserInfoMapper.findUserByUserName(userName);
        }
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("userInfo", user);
        dataMap.put("sysRoleVoList", this.getStrByList(this.getRoleByUserId(user.getUserInfoNo()),"AR_CODE"));
        if("pc".equals(loginType)) {
            List<Menu> sysMenuVoList = this.createMenu(userName, user.getUserInfoNo());
            List<Map<String,Object>> rolePermissionVoList = this.getResourceByUserId(user.getUserInfoNo());
            dataMap.put("rolePermissionVoList", rolePermissionVoList);
            dataMap.put("rolePermissionVoStr", this.getStrByList(rolePermissionVoList,"PERMISSION"));
            dataMap.put("sysMenuVoList", sysMenuVoList);
        }
        //保存用户信息
        request.getSession().setAttribute(Constant.LOGIN_USER, user);
        return this.loginReturnMap(user, dataMap);
    }
    public String getStrByList(List<Map<String,Object>> list, String key) throws Exception{
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<list.size();i++){
            if(null != list.get(i).get(key) && !"".equals(list.get(i).get(key).toString())){
                sb.append(list.get(i).get(key).toString()).append(",");
            }
        }
        return sb.toString();
    }
    public List<Map<String,Object>> getRoleByUserId(String auId) throws Exception{
        List<Map<String,Object>> list = t61SysUserInfoMapper.getRoleByUserId(auId);
        return list;
    }
    public List<Map<String,Object>> getResourceByUserId(String auId) throws Exception{
        List<Map<String,Object>> list = t61SysUserInfoMapper.getResourceByUserId(auId);
        return list;
    }
    /**
     * 处理登录返回信息
     * @author yangcd
     * @param user 用户对象
     * @param dataMap 返回的data数据
     * @return map 返回map信息
     * */
    private Map<String, Object> loginReturnMap(SysUserInfo user, Map<String, Object> dataMap) throws Exception{
        //保存用户信息
        String token = "TOKEN:"+ IdUtils.getIncreaseIdByNanoTime();
        RedisUtil.set(token, JSONObject.toJSONString(user));
        RedisUtil.set("USER_ID:"+user.getUserInfoNo(), token);
        String aesKey = "AES_KEY:"+token;
        String aesValue = RandomStringUtils.randomAlphanumeric(16);
        RedisUtil.set(aesKey, aesValue);

        RedisUtil.set("USER_ROLE:"+user.getUserInfoNo(), dataMap.get("sysRoleVoList").toString());
//		RedisUtil.expire("USER_ROLE:"+user.getUserId(), 1800);

        Map<String, Object> map = new HashMap<String, Object>();

        map.put("status", "SUCCESS");
        map.put("message", "登陆成功");
        map.put("token", token);
        map.put("aesKey", aesValue);
        map.put("data", dataMap);
        map.put("sucess", true);
        return map;

    }
    /**
     * 查询资源信息，构建资源树结构
     * @param auId
     * */
    public List<Menu> createMenu(String loginName, String auId)  throws Exception{
        // 原始的数据
        List<Menu> menuList = t61SysUserInfoMapper.selectAll(loginName, auId);
        // 最后的结果
        List<Menu> menuAllList = new ArrayList<Menu>();
        // 先找到所有的一级菜单
        for (int i = 0; i < menuList.size(); i++) {
            menuList.get(i).setStatus(false);
            // 一级菜单parentId为0
            if ("0".equals(menuList.get(i).getParentId())) {
                menuList.get(i).setStatus(true);
                menuAllList.add(menuList.get(i));
            }
        }
        // 为一级菜单设置子菜单，getChild是递归调用的
        for (Menu menu : menuAllList) {
            menu.setSysMenuVoChild(this.getChild(menu.getId(), menuList));
            menu.setChildren(this.getChild(menu.getId(), menuList));
        }
        return menuAllList;
    }

    /**
     * 递归查找子菜单及资源
     * @return
     */
    private List<Menu> getChild(String id, List<Menu> rootMenu) {
        List<Menu> childList = new ArrayList<>();
        for (Menu menu : rootMenu) {
//			if (!menu.getStatus()) {
            if (menu.getParentId().equals(id)) {
//					menu.setStatus(true);
                childList.add(menu);
            }
//			}
        }
        for (Menu menu : childList) {
            List<Menu> child = getChild(menu.getId(), rootMenu);
            menu.setSysMenuVoChild(child);
            menu.setChildren(child);
        }
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }
}
